package com.desksoft.ecommerce.util.html.element.query;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;

import com.desksoft.ecommerce.util.html.PageXml;
import com.desksoft.ecommerce.util.html.element.QueryElement;
import com.desksoft.utility.encode.EncodeUtil;

import freemarker.template.utility.StringUtil;

/***************************************
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: 
 * 创建作者：luoy
 * 文件名称：Sql查询元素
 * 版本：
 * 功能：
 * 最后修改时间：
 * 修改记录：
 *****************************************/
public class QuerySqlElement extends QueryElement {

	protected List<String> tableNameL;		// 	表名
	protected String sql;					//	Sql语句
	
	protected PageXml pageXml;
	
	public QuerySqlElement() {
		super();
	}

	public QuerySqlElement(Element element, PageXml pageXml){
		this.pageXml = pageXml;
		this.sql = element.element("sql").getText();
		this.tableNameL = this.getTableList(element);
		
		replaceSql();
		parseSql();
		
		try {
			this.sql = EncodeUtil.encipherment(this.sql, "sql");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 替换sql语句中的变量
	 */
	public void replaceSql(){
		this.sql = this.pageXml.getVarCollection().replaceSql(this.sql);
	}
	
	/**
	 * 解析Sql语句
	 */
	public void parseSql(){
		
		//	取select和from之间的部分
		int index_select = this.sql.indexOf("select")+6;
		int index_from = this.sql.indexOf("from");
		String fieldStr = this.sql.substring(index_select,index_from).trim();
		String[] columnNameA = fieldStr.split(",");
		this.queryFields = new QueryField[columnNameA.length];
		for (int i=0;i<columnNameA.length;i++){
			this.queryFields[i] = new QueryField(columnNameA[i],"");
		}
	}
	
	/**
	 * 解析表
	 * @return
	 */
	public List<String> getTableList(Element element){
		List<Element> elementL = element.elements("table");
		List<String> tableL = new ArrayList<String>(elementL.size());
		for (Element e:elementL){
			tableL.add(e.attributeValue("name"));
		}
		return tableL;
	}
	
	public List<String> getTableNameL() {
		return tableNameL;
	}
	public String getTables(){
		String tables = "";
		if (this.getTableNameL()!=null && this.getTableNameL().size()>0){
			tables = this.getTableNameL().get(0);
			for (int i=1;i<this.getTableNameL().size();i++){
				tables = tables + "," +this.getTableNameL().get(i);
			}
		}
		return tables;
	}
	public void setTableNameL(List<String> tableNameL) {
		this.tableNameL = tableNameL;
	}
	public String getSql() {
		return sql;
	}
	public void setSql(String sql) {
		this.sql = sql;
	}

	
}
